<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="patientName">
        <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="床号" prop="visitBed">
        <el-input
            v-model="queryParams.visitBed"
            placeholder="请输入患者床号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊科室" prop="deptId">
        <el-tree-select
            v-model="queryParams.deptId"
            :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择就诊科室"
            check-strictly
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="visitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="patientName" />
      <el-table-column label="就诊号" align="center" prop="visitCode" />
      <el-table-column label="床号" align="center" prop="visitBed" />
      <el-table-column label="就诊医生" align="center" prop="visitDoctorName" />
      <el-table-column label="性别" align="center" prop="patientSex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.patientSex" />
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="patientPhone" />
      <el-table-column label="身份证号" align="center" width="180" prop="patientCard" />
      <el-table-column label="年龄" align="center" prop="visitAge" />
      <el-table-column label="就诊日期" align="center" prop="visitDate" width="180"/>
      <el-table-column label="就诊科室" align="center" prop="deptName" />
      <el-table-column label="就诊状态" align="center" prop="visitStatus">
        <template #default="scope">
          <dict-tag :options="patient_visit_status" :value="scope.row.visitStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改患者就诊信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="visitRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="patientCard">
              <el-input v-model="form.patientCard" @change="getPatientInByCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="就诊医生" prop="visitDoctor">
              <el-select v-model="form.visitDoctor" placeholder="请选择医生">
                <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="patientName">
              <el-input v-model="form.patientName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床号" prop="visitBed">
              <el-input v-model="form.visitBed" placeholder="请输入患者床号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="就诊日期" prop="visitDate">
              <el-date-picker clearable
                              v-model="form.visitDate"
                              type="datetime"
                              format="YYYY-MM-DD HH:mm:ss"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              :editable="false"
                              placeholder="请选择就诊日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="deptId">
              <el-tree-select
                  v-model="form.deptId"
                  :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="请选择就诊科室"
                  check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="就诊号" prop="visitCode">
              <el-input v-model="form.visitCode" placeholder="请输入就诊号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="patientSex">
              <el-select v-model="form.patientSex" placeholder="请选择性别">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="patientPhone">
              <el-input v-model="form.patientPhone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="visitAge">
              <el-input v-model="form.visitAge" placeholder="请输入患者就诊年龄" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="patient">
import { listVisit, getVisit, delVisit, addVisit, updateVisit, selectPatientRecord } from "@/api/pages/patient/patient";
import { listUser } from "@/api/system/user";

import { deptTreeSelect } from "@/api/system/user";
import {idCard} from "@/utils/ruoyi.js";

const { proxy } = getCurrentInstance();
const { sys_user_sex, patient_visit_status } = proxy.useDict("sys_user_sex", "patient_visit_status");

const visitList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const userList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientName: null,
    visitBed: null,
    deptId: null,
  },
  userParams: {

  },
  rules: {
    patientCard: [
      {required: true,
      pattern: /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
      message: "请输入正确的身份证号",
      trigger: "blur"}
    ],
    patientName: [
      { required: true, message: "姓名不能为空", trigger: "blur" },
      { min: 1, max: 20, message: "姓名长度必须介于 1 和 20 之间", trigger: "blur" }
    ],
    visitBed: [
      { required: true, message: "床号不能为空", trigger: "blur" },
      { min: 1, max: 5, message: "床号长度必须介于 1 和 5 之间", trigger: "blur" }
    ],
    visitDate: [
      { required: true, message: "就诊日期不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "科室不能为空", trigger: "blur" }
    ],
    visitDoctor: [
      { required: true, message: "医生不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, userParams, form, rules } = toRefs(data);

/** 查询患者就诊信息列表 */
function getList() {
  loading.value = true;
  listVisit(queryParams.value).then(response => {
    visitList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    visitId: null,
    patientName: null,
    patientCard: null,
    patientSex: null,
    patientPhone: null,
    visitDate: null,
    visitCode: null,
    visitAge: null,
    visitBed: null,
    visitDoctor: null,
    deptId: null,
    remark: null
  };
  proxy.resetForm("visitRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.visitId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加患者就诊信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row;
  open.value = true;
  title.value = "修改患者就诊信息";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["visitRef"].validate(valid => {
    if (valid) {
      if (form.value.visitId != null) {
        updateVisit(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVisit(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _visitIds = row.visitId || ids.value;
  proxy.$modal.confirm('是否确认删除患者就诊信息编号为"' + _visitIds + '"的数据项？').then(function() {
    return delVisit(_visitIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('stick/visit/export', {
    ...queryParams.value
  }, `visit_${new Date().getTime()}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 根据身份证号查询患者信息*/
function getPatientInByCard(patientCard){
  selectPatientRecord(patientCard).then(response => {
    if (response.data != null) {
      form.value = {
        visitId: form.value.visitId,
        patientName: response.data.patientName,
        patientCard: form.value.patientCard,
        patientSex: response.data.patientSex,
        patientPhone: response.data.patientPhone,
        visitDate: form.value.visitDate,
        visitCode: form.value.visitCode,
        visitAge: form.value.visitAge,
        visitBed: form.value.visitBed,
        deptId: form.value.deptId,
        remark: form.value.remark
      };
    } else {
      let sex = idCard(patientCard, 2);
      let age = idCard(patientCard, 3);
      form.value = {
        visitId: form.value.visitId,
        patientName: form.value.patientName,
        patientCard: form.value.patientCard,
        patientSex: sex,
        patientPhone: form.value.patientPhone,
        visitDate: form.value.visitDate,
        visitCode: form.value.visitCode,
        visitAge: age,
        visitBed: form.value.visitBed,
        deptId: form.value.deptId,
        remark: form.value.remark
      };
    }
  })
}

/** 查询用户列表 */
function getUserList() {
  listUser(userParams.value).then(response => {
    userList.value = response.rows;
    console.log("医生:", response.rows)
  });
}

getUserList();
getDeptTree();
getList();
</script>
